package com.simple.template.demo004;

import java.util.HashMap;
import java.util.Map;

public class ShoppingContext {
    /**
     * 存储具体的策略
     */
    private Map<String,String> strategyMap;
    private static ShoppingContext instance;

    private ShoppingContext(){
        this.init();
    }
    /**
     * 初始化具体策略的映射关系
     */
    private void init(){
        this.strategyMap = new HashMap<>();
        this.strategyMap.put("1","com.simple.template.demo004.Shopping_lisi");
        this.strategyMap.put("2","com.simple.template.demo004.Shopping_zhangsan");
    }

    public static ShoppingContext getInstance() {
        if (instance == null) {
            synchronized (ShoppingContext.class) {
                if (instance == null) {
                    instance = new ShoppingContext();
                }
            }
        }
        return instance;
    }
    public Shopping getStrategy(String strategyCode){
        try {
            String className = this.strategyMap.get(strategyCode);
            Class<?> clazz = Class.forName(className);
            return (Shopping) clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
